const pool = require('../config/db');

// 获取问卷列表
const getSurveys = async (req, res) => {
  try {
    const { page = 1, limit = 10, status,title,pageSize } = req.query;
    const offset = (page - 1) * pageSize;

    let query = `
      SELECT *
      FROM surveys s
      WHERE 1=1
    `;
    const params = [];

    // 状态筛选
    if (status) {
      query += ' AND s.status = ?';
      params.push(status);
    }


    // 关键词搜索
    if (title) {
      query += ' AND (s.title LIKE ? )';
      const searchPattern = `%${title}%`;
      params.push(searchPattern);
    }

    // 添加分页
    query += ' LIMIT ? OFFSET ?';
    params.push(parseInt(pageSize), offset);

    // 执行查询
    console.log('分页查询:', query);
    const [surveys] = await pool.query(query, params);
    

    // 获取总数
    let countQuery = 'SELECT COUNT(*) as total FROM surveys s WHERE 1=1';
    const countParams = [];

    if (status) {
      countQuery += ' AND s.status = ?';
      countParams.push(status);
    }

    if (title) {
      countQuery += ' AND (s.title LIKE ? )';
      const searchPattern = `%${title}%`;
      countParams.push(searchPattern);
    }
    console.log('t', countParams);
    console.log('total查询:', countQuery);
    const [totalResult] = await pool.query(countQuery, countParams);
    

    res.json({
      code: 200,
      message: '查询成功',
      data: {
        list: surveys,
        total: totalResult[0].total,
        page: parseInt(page),
        limit: parseInt(limit)
      }
      
    });
  } catch (error) {
    console.error('查询问卷列表错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 删除问卷
const deleteSurvey = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 验证id参数
    if (!id || isNaN(id)) {
      return res.status(400).json({
        code: 400,
        message: '无效的问卷ID'
      });
    }

    // 检查问卷是否存在
    const [survey] = await pool.query('SELECT * FROM surveys WHERE id = ?', [id]);
    if (survey.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '问卷不存在'
      });
    }

    // 执行删除操作
    await pool.query('DELETE FROM surveys WHERE id = ?', [id]);
    res.json({
      code: 200,
      message: '删除成功'
    });
  } catch (error) {
    console.error('删除问卷错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};
 // 获取问卷详情
const getSurveyDetail = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 获取问卷基本信息
    const [surveys] = await pool.query(
      `SELECT *
       FROM surveys s
       WHERE s.id = ?`,
      [id]
    );

    if (surveys.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '问卷不存在'
      });
    }

    const survey = surveys[0];
    
    // 获取问题列表
    const [questions] = await pool.query(
      'SELECT * FROM questions WHERE survey_id = ? ORDER BY order_num',
      [id]
    );

    // 获取每个问题的选项
    for (let question of questions) {
      const [options] = await pool.query(
        'SELECT * FROM options WHERE question_id = ? ORDER BY order_num',
        [question.id]
      );
      question.options = options;
    }

    survey.questions = questions;
    res.json({
      code: 200,
      message: '查询成功',
      data: survey
    });
  } catch (error) {
    console.error('查询问卷详情错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 更新问卷（保存/发布）
const updateSurvey = async (req, res) => {
  try {
    const { id } = req.params;
    const { title, description, end_time, type, questions, status } = req.body;
    
    // 验证id参数
    if (!id || isNaN(id)) {
      return res.status(400).json({
        code: 400,
        message: '无效的问卷ID'
      });
    }

    // 检查问卷是否存在
    const [survey] = await pool.query('SELECT * FROM surveys WHERE id = ?', [id]);
    if (survey.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '问卷不存在'
      });
    }

    // 验证状态值是否有效
    const validStatus = ['draft', 'active', 'ended'];
    const surveyStatus = validStatus.includes(status) ? status : survey[0].status;

    // 处理end_time，确保它是有效的日期格式或null
    let formattedEndTime = null;
    if (end_time) {
      formattedEndTime = new Date(end_time);
      // 检查日期是否有效
      if (isNaN(formattedEndTime.getTime())) {
        formattedEndTime = null;
      }
    }

    // 更新问卷基本信息
    await pool.query(
      `UPDATE surveys 
       SET title = ?, description = ?, end_time = ?, type = ?, status = ?, updated_at = NOW() 
       WHERE id = ?`,
      [title, description, formattedEndTime, type, surveyStatus, id]
    );

    // 删除原有问题和选项
    const [existingQuestions] = await pool.query('SELECT id FROM questions WHERE survey_id = ?', [id]);
    for (const question of existingQuestions) {
      await pool.query('DELETE FROM options WHERE question_id = ?', [question.id]);
    }
    await pool.query('DELETE FROM questions WHERE survey_id = ?', [id]);

    // 添加新问题和选项
    if (questions && questions.length > 0) {
      for (let i = 0; i < questions.length; i++) {
        const question = questions[i];
        const [result] = await pool.query(
          'INSERT INTO questions (survey_id, type, content, required, order_num) VALUES (?, ?, ?, ?, ?)',
          [id, question.type, question.content, question.required ? 1 : 0, i]
        );
        
        const questionId = result.insertId;
        
        // 添加选项（如果有）
        if (['single', 'multiple'].includes(question.type) && question.options && question.options.length > 0) {
          for (let j = 0; j < question.options.length; j++) {
            const option = question.options[j];
            await pool.query(
              'INSERT INTO options (question_id, content, order_num) VALUES (?, ?, ?)',
              [questionId, option.content, j]
            );
          }
        }
      }
    }

    res.json({
      code: 200,
      message: status === 'active' ? '问卷发布成功' : '问卷保存成功'
    });
  } catch (error) {
    console.error('更新问卷错误:', error);
    console.error('错误详情:', error.message);
    console.error('错误堆栈:', error.stack);
    
    // 提供更详细的错误信息
    let errorMessage = '服务器错误';
    if (error.code === 'ER_BAD_NULL_ERROR') {
      errorMessage = '数据格式错误: 必填字段不能为空';
    } else if (error.code === 'ER_DATA_TOO_LONG') {
      errorMessage = '数据过长: 某些字段超出了允许的长度';
    } else if (error.code === 'ER_NO_REFERENCED_ROW') {
      errorMessage = '引用错误: 关联的数据不存在';
    }
    
    res.status(500).json({
      code: 500,
      message: errorMessage,
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

// 获取仪表盘数据
const getDashboardData = async (req, res) => {
  try {
    // 获取问卷总数
    const [totalSurveysResult] = await pool.query('SELECT COUNT(*) as total FROM surveys');
    const totalSurveys = totalSurveysResult[0].total;

    // 获取活跃问卷数
    const [activeSurveysResult] = await pool.query("SELECT COUNT(*) as total FROM surveys WHERE status = 'active'");
    const activeSurveys = activeSurveysResult[0].total;

    // 获取今日填写数
    const today = new Date().toISOString().split('T')[0];
    const [todayResponsesResult] = await pool.query(
      'SELECT COUNT(*) as total FROM responses WHERE DATE(created_at) = ?',
      [today]
    );
    const todayResponses = todayResponsesResult[0].total;

    // 获取问卷状态分布
    const [statusDistribution] = await pool.query(
      'SELECT status as name, COUNT(*) as value FROM surveys GROUP BY status'
    );

    // 获取最近7天的填写趋势
    const [weeklyTrend] = await pool.query(
      `SELECT 
        DATE(created_at) as date, 
        COUNT(*) as count 
      FROM responses 
      WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY) 
      GROUP BY DATE(created_at) 
      ORDER BY date`
    );

    // 获取最近创建的问卷
    const [recentSurveys] = await pool.query(
      'SELECT id, title, status, created_at FROM surveys ORDER BY created_at DESC LIMIT 5'
    );

    // 获取最近填写的问卷
    const [recentResponses] = await pool.query(
      `SELECT 
        r.id, 
        r.survey_id, 
        s.title, 
        u.username as respondent, 
        r.created_at as submit_time 
      FROM responses r 
      JOIN surveys s ON r.survey_id = s.id 
      LEFT JOIN users u ON r.user_id = u.id 
      ORDER BY r.created_at DESC 
      LIMIT 5`
    );

    res.json({
      code: 200,
      message: '获取仪表盘数据成功',
      data: {
        totalSurveys,
        activeSurveys,
        todayResponses,
        statusDistribution,
        weeklyTrend,
        recentSurveys,
        recentResponses
      }
    });
  } catch (error) {
    console.error('获取仪表盘数据错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 创建问卷
const createSurvey = async (req, res) => {
  try {
    const { title, description, end_time, type, questions, status } = req.body;
    
    // 验证必填字段
    if (!title) {
      return res.status(400).json({
        code: 400,
        message: '问卷标题不能为空'
      });
    }

    // 验证状态值是否有效
    const validStatus = ['draft', 'active', 'ended'];
    if (status && !validStatus.includes(status)) {
      return res.status(400).json({
        code: 400,
        message: '无效的问卷状态'
      });
    }

    // 处理end_time，确保它是有效的日期格式或null
    let formattedEndTime = null;
    if (end_time) {
      formattedEndTime = new Date(end_time);
      // 检查日期是否有效
      if (isNaN(formattedEndTime.getTime())) {
        return res.status(400).json({
          code: 400,
          message: '无效的结束时间格式'
        });
      }
    }

    // 创建问卷基本信息
    const [result] = await pool.query(
      `INSERT INTO surveys (title, description, end_time, type, status, created_at, updated_at) 
       VALUES (?, ?, ?, ?, ?, NOW(), NOW())`,
      [title, description, formattedEndTime, type || 'public', status || 'draft']
    );
    
    const surveyId = result.insertId;
    
    // 添加问题和选项
    if (questions && questions.length > 0) {
      for (let i = 0; i < questions.length; i++) {
        const question = questions[i];
        const [questionResult] = await pool.query(
          'INSERT INTO questions (survey_id, type, content, required, order_num) VALUES (?, ?, ?, ?, ?)',
          [surveyId, question.type, question.content, question.required ? 1 : 0, i]
        );
        
        const questionId = questionResult.insertId;
        
        // 添加选项（如果有）
        if (['single', 'multiple'].includes(question.type) && question.options && question.options.length > 0) {
          for (let j = 0; j < question.options.length; j++) {
            const option = question.options[j];
            await pool.query(
              'INSERT INTO options (question_id, content, order_num) VALUES (?, ?, ?)',
              [questionId, option.content, j]
            );
          }
        }
      }
    }

    res.status(201).json({
      code: 201,
      message: status === 'active' ? '问卷发布成功' : '问卷保存成功',
      data: {
        id: surveyId
      }
    });
  } catch (error) {
    console.error('创建问卷错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

module.exports = {
  getSurveys,
  getSurveyDetail,
  deleteSurvey,
  updateSurvey,
  getDashboardData,
  createSurvey
};